//
//  ViewController.m
//  AudioConvertOC
//
//  Created by xyanl on 2025/4/26.
//

#import "ViewController.h"
#import "SpeechManager.h"
#import "LameAudioConvert.h"
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()<SpeechManagerDelegate, AVAudioRecorderDelegate>

@property (weak, nonatomic) IBOutlet UILabel *resultLabel;

@property (nonatomic, strong) SpeechManager *speech;

/// 音频录音机
@property (nonatomic,strong) AVAudioRecorder *audioRecorder;
/// 音频保存路径
@property (nonatomic, copy) NSString *audioPath;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.speech requestAuthorization];
}

- (SpeechManager *)speech {
    if (_speech == nil) {
        _speech = [[SpeechManager alloc] init];
        _speech.delegate = self;
    }
    return  _speech;
}


- (IBAction)m4aToMp3Action:(UIButton *)sender {
    
    // audioM4A
    NSString * audioM4AUrl = [[NSBundle mainBundle] pathForResource:@"audioM4A" ofType:@".m4a"];
    
    NSString *outPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"resultM4A.mp3"];
    
    // 将 M4A 音频文件转写
    // [self.speech createSpeech:@"zh_CN" url:audioM4AUrl];
    
    // 将 M4A 音频文件转成 PM3 文件后,再转写
    [LameAudioConvert convertM4aToMp3:audioM4AUrl mp3Path:outPath completion:^(BOOL success) {
        if (success) {
            [[SpeechManager shareInstance] createSpeech:@"zh_CN" url:outPath completion:^(BOOL success, NSString * _Nonnull result) {
                NSLog(@"转写结果 completion: %@", result);
                self.resultLabel.text = result;
            }];
        }
    }];
    
}

- (IBAction)pcmToMp3Action:(id)sender {
    // audioPCM
    NSString * audioPCMUrl = [[NSBundle mainBundle] pathForResource:@"audioPCM" ofType:@".caf"];
    
    NSString *outPath =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"resultPCM.mp3"];
    
    // 将 PCM 音频文件转写
    // [self.speech createSpeech:@"zh_CN" url:audioM4AUrl];
    
    // 将 PCM 音频文件转成 PM3 文件后,再转写
    [LameAudioConvert convertPcmToMp3:audioPCMUrl mp3Path:outPath completion:^(BOOL success) {
        if (success) {
            [self.speech createSpeech:@"zh_CN" url:outPath];
        }
    }];
    
}


- (IBAction)startRecorderAction:(UIButton *)sender {
    
    sender.selected = !sender.isSelected;
    
    if (!sender.isSelected) {
        // 被选中, 要停止录音
        NSLog(@"停止录音");
        [self stopRecord];
        return;
    }
    
    // 创建录音文件保存路径
    self.audioPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.caf", [self currentTimestamp]]];
    //创建录音文件保存路径
    NSURL *url = [NSURL URLWithString:self.audioPath];
    // 创建录音格式设置
    NSDictionary *setting = [self getAudioPCMSetting];
    //创建录音机
    NSError *error = nil;
    
    self.audioRecorder = [[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
    self.audioRecorder.delegate = self;
    self.audioRecorder.meteringEnabled = YES;//如果要监控声波则必须设置为YES
    [self startRecorder];
}

// 转写录音文件
- (IBAction)convertAudioAction:(UIButton *)sender {
    // [self.speech createSpeech:@"zh_CN" url:self.audioPath];
    [self.speech createSpeech:@"ru-RU" url:self.audioPath];
    
}

- (NSDictionary *)getAudioM4aSetting {
    return @{
        // 录音格式 无法使用
        AVFormatIDKey: @(kAudioFormatMPEG4AAC),
        // 采样率
        AVSampleRateKey: @(8000.0),
        // 通道数
        AVNumberOfChannelsKey: @(1),
        // 线性采样位数
        AVLinearPCMBitDepthKey: @(16),
        // 音频质量,采样质量
        AVEncoderAudioQualityKey: @(AVAudioQualityMedium)
    };
}

- (NSDictionary *)getAudioPCMSetting {
    //LinearPCM 是iOS的一种无损编码格式,但是体积较为庞大
    return @{
        // 录音格式 无法使用
        AVFormatIDKey: @(kAudioFormatLinearPCM),
        // 采样率
        AVSampleRateKey: @(11025.0), // 44100.0
        // 通道数
        AVNumberOfChannelsKey: @(2),
        // 线性采样位数
        AVLinearPCMBitDepthKey: @(16),
        // 音频质量,采样质量
        AVEncoderAudioQualityKey: @(AVAudioQualityMin)
    };
}

- (void)startRecorder {
    if (!self.audioRecorder) {
        return;
    }
    if ([self.audioRecorder isRecording]) {
        [self.audioRecorder stop];
    }
    NSLog(@"----------开始录音----------");
    [self deleteOldRecordFile];
    
    AVAudioSession *audioSession=[AVAudioSession sharedInstance];
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    
    if (![self.audioRecorder isRecording]) {// 0--停止、暂停，1-录制中
        // 首次使用应用时如果调用record方法会询问用户是否允许使用麦克风
        [self.audioRecorder record];
    }
}

- (void)stopRecord {
    if (self.audioRecorder) {
        NSLog(@"文件路径 %@", self.audioPath);
        [self.audioRecorder stop];
        self.audioRecorder = nil;
    }
}

#pragma mark - 删除录音文件
- (void)deleteOldRecordFile {
    NSFileManager* fileManager = [NSFileManager defaultManager];
    
    BOOL isHave = [[NSFileManager defaultManager] fileExistsAtPath:self.audioPath];
    
    if (!isHave) {
        NSLog(@"不存在");
    }else {
        NSLog(@"存在");
        BOOL isDele= [fileManager removeItemAtPath:self.audioPath error:nil];
        if (isDele) {
            NSLog(@"删除成功");
        }else {
            NSLog(@"删除失败");
        }
    }
}

#pragma mark - SpeechManagerDelegate
- (void)didFinishRecognition:(NSString *)result isSuccess:(BOOL)isSuccess {
    if (isSuccess) {
        self.resultLabel.text = result;
        
    } else {
        NSLog(@"音频转写失败");
    }
}

/// 当前时间戳
- (int)currentTimestamp {
    return (int)[[NSDate date] timeIntervalSince1970];
}


@end
